<!--
 * @Project_description: 用户添加编辑
-->
<template>
  <div class='user-add'>
    <el-dialog v-drag :before-close='handleClose' :title='title' :visible.sync='dialogVisible' width='33%'>
      <el-form ref='form' :disabled='loading' :model='form' :rules='rules' label-width='100px'>
        <el-form-item label='角色' prop='role'>
          <avue-select v-model='userRole' :clearable='false' :dic='dic' all multiple placeholder='请选择角色'
                       type='tree'></avue-select>
        </el-form-item>
      </el-form>
      <!-- 下放按钮 -->
      <span slot='footer' class='dialog-footer'>
        <el-button :loading='loading' type='primary' @click='onSuccess'>保 存</el-button>
        <el-button @click='dialogVisible = false'>取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'sys-user-role',
  data() {
    // 这里存放数据
    return {
      dialogVisible: false,
      loading: false,
      title: '设置角色',
      form: {},
      userId: '',
      rules: {},
      //当前用户的角色
      userRole: [],
      //当前系统中的角色
      dic: [],
    }
  },
  // 方法集合
  methods: {
    //初始化
    init(id) {
      let _this = this
      this.userId = id
      this.dialogVisible = true
      this.getRole()
      //移除表单校验结果
      setTimeout(() => {
        _this.$refs.form.clearValidate()
        _this._getRules(_this.$refs.form)
      })
    },
    //获取用户角色
    async getUserRole() {
      let res = await this.$api.user.userRole({ userId: this.userId })
      this.userRole = res.data.map(i => i.roleId)
    },
    //获取所有角色
    async getRole(role) {
      let request = {
        pageSize: 9999,
        pageNo: 1,
        state: 0,
      }
      let res = await this.$api.role.list(request)
      //循环
      res.data.rows.forEach(i => {
        i.label = i.roleName
        i.desc = i.intro.length < 10 ? i.intro : i.intro.slice(0, 10) + '..'
        i.value = i.roleId
      })
      this.dic = res.data.rows
      await this.getUserRole()
    },
    // 关闭
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
        })
        .catch((_) => {
        })
    },
    // 修改状态
    isFalse() {
    },
    //提交
    async onSuccess() {
      let _this = this
      _this.$refs.form.validate(async (valid) => {
        if (valid) {
          _this.loading = true
          try {

            await _this.$api.user.adduserRole({ userId: _this.userId, roleIds: _this.userRole })
            _this.$message.success('设置成功')
            await _this.$emit('load')
            _this.dialogVisible = false
            _this.loading = false
          } catch (error) {
            _this.loading = false

          }
        } else {
          console.log('validate error')
        }
      })
    },
  },
}
</script>

<style lang='scss' scoped>
//@import url(); 引入公共css类
</style>
